package com.yonginitagmaker.util;

import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONObject;

import ra.genius.net.GLog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.DynamicDrawableSpan;
import android.text.style.ImageSpan;
import android.widget.EditText;

public class FormatUtil
{
	private static double	distance	= 1;

	// private static double distance = 1000.0;

	/**
	 * null 체크
	 * 
	 * @param targetString
	 * @return null이면 true, null이 아니면 false 반환
	 */
	public static boolean isNullorEmpty(String targetString)
	{
		if(targetString == null || targetString.trim().equals("") || targetString.trim().equals("null"))
			return true;

		return false;
	}

	public static String toPriceFormat(double lSource, boolean hasWon)
	{
		String won = "원";

		if((lSource != 0.0) && (lSource % 10000 == 0) && hasWon)
		{
			won = "만원";
			lSource = lSource / 10000;
		}
		String sPattern = "###,###,###,###,###,##0";
		DecimalFormat decimalformat = new DecimalFormat(sPattern);

		String result = decimalformat.format(lSource);
		result = hasWon ? result + won : result + "";
		return result;
	}

	public static String toPriceFormat(String sSource, boolean hasWon)
	{
		double number = 0.0;
		try
		{
			number = Double.valueOf(sSource);
		}
		catch (NumberFormatException e)
		{
			GLog.w(e.getMessage());
		}

		return toPriceFormat(number, hasWon);
	}

	public static String getKmData(String km)
	{
		String retVal = "";
		double dKm = 0.0;
		try
		{
			dKm = Double.parseDouble(km);

			DecimalFormat format = new DecimalFormat("0.00");
			retVal = format.format(dKm / (distance)) + "km";
		}
		catch (Exception e)
		{
			retVal = "0.00km";
		}
		return retVal;

	}

	public static String getKmData(double km)
	{
		String retVal = "0";
		if(km < 0)
		{
			retVal = "";
		}
		else if(km < 1000.0)
		{
			retVal = (int) km + "m";
		}
		else
		{
			double value = 0;
			value = km / (distance);
			DecimalFormat format = new DecimalFormat("0.00");
			retVal = format.format(value) + "km";
		}

		return retVal;

	}

	public static String convertTwoNumber(long day)
	{
		String temp = "0" + day;

		return temp.substring(temp.length() - 2, temp.length());
	}

	public static int convertOneNumber(long num)
	{
		String str = String.valueOf(num);
		if(str.startsWith("0"))
		{
			str.substring(str.length() - 1, str.length());
		}
		return Integer.parseInt(str);
	}

	public static String convertMD5(String str)
	{
		MessageDigest md5 = null;
		try
		{
			md5 = MessageDigest.getInstance("MD5");
		}
		catch (Exception e)
		{
			GLog.w(e.getMessage());
		}

		String eip;
		byte[] bip;

		String temp = "";
		String tst = str;

		bip = md5.digest(tst.getBytes());

		for (int i = 0; i < bip.length; i++)
		{
			eip = "" + Integer.toHexString(bip[i] & 0x000000ff);
			if(eip.length() < 2)
				eip = "0" + eip;

			temp = temp + eip;
		}

		return temp;

	}

	/**
	 * 천단위로 자동으로 콤마를 찍어준다.
	 * 
	 * @param et
	 * @return
	 */
	public static EditText setAutoPriceComma(final EditText et)
	{
		et.addTextChangedListener(new TextWatcher()
		{
			String	strPrice	= "";

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after)
			{
			}

			@Override
			public void afterTextChanged(Editable s)
			{
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
				if(!s.toString().equals(strPrice))
				{
					strPrice = FormatUtil.toPriceFormat(s.toString().replace(",", ""), false);
					et.setText(strPrice);
					Editable e = et.getText();
					Selection.setSelection(e, strPrice.length());
				}
			}
		});

		return et;
	}

	/**
	 * 이메일 패턴검사
	 * 
	 * @param email
	 * @return
	 */
	public static boolean isEmailPattern(String email)
	{
		if(isNullorEmpty(email))
		{
			return false;
		}
		Pattern pattern = Pattern.compile("\\w+[@]\\w+\\.\\w+");
		Matcher match = pattern.matcher(email);
		return match.find();
	}

	public static Date FormatStringGetDate(String dateAndTimeStr, String formatStr)
	{
		SimpleDateFormat fromFormat = new SimpleDateFormat(formatStr);
		Date fromDate = null;
		try
		{
			fromDate = fromFormat.parse(dateAndTimeStr);
		}
		catch (Exception e)
		{
			fromDate = new Date();
		}

		return fromDate;
	}

	public static String FormatDateConvertString(String dateAndTimeStr, String formatStr, String retformatStr)
	{
		if(isNullorEmpty(dateAndTimeStr))
			return "";

		SimpleDateFormat fromFormat = new SimpleDateFormat(formatStr);
		SimpleDateFormat toFormat = new SimpleDateFormat(retformatStr);

		Date fromDate = null;
		try
		{
			fromDate = fromFormat.parse(dateAndTimeStr);
		}
		catch (Exception e)
		{
			fromDate = new Date();
		}

		return toFormat.format(fromDate);
	}

	public static String FormatDateGetString(Date date, String formatStr)
	{
		String strDate = "";

		// LogUtil.e(formatStr);

		SimpleDateFormat fromFormat;
		fromFormat = new SimpleDateFormat(formatStr);
		try
		{
			strDate = fromFormat.format(date.getTime());
		}
		catch (Exception e)
		{
			e.printStackTrace();
			date = new Date();
			strDate = fromFormat.format(date.getTime());
		}

		return strDate;
	}

	/**
	 * input : dateString
	 * 
	 * @return calendar
	 */
	public static Calendar FormatStringGetCalendar(String dateAndTimeStr, String formatStr)
	{
		SimpleDateFormat fromFormat = new SimpleDateFormat(formatStr);
		Calendar cal = new GregorianCalendar();
		Date fromDate = null;
		try
		{
			fromDate = fromFormat.parse(dateAndTimeStr);
		}
		catch (Exception e)
		{
			fromDate = new Date();
		}

		cal.setTime(fromDate);

		return cal;
	}

	public static String FormatCalendarGetString(Calendar cal, String formatStr)
	{
		SimpleDateFormat fromFormat = new SimpleDateFormat(formatStr);
		return fromFormat.format(cal.getTime());
	}

	public static String FormatCalendarGetDayOfWeek(Calendar cal)
	{
		String[] dayOfWeek = { "", "일", "월", "화", "수", "목", "금", "토" };
		return dayOfWeek[cal.get(Calendar.DAY_OF_WEEK)];
	}

	/**
	 * 특정 시간의 오전/오후 정보를 가져온다.
	 * 
	 * @param strDate
	 *            "hh:mm" 형태로 특정시간를 입력
	 * @return 오전 or 오후 를 반환
	 */
	public static String getAmPm(String strDate)
	{
		Locale locale = java.util.Locale.KOREA;
		SimpleDateFormat sdf = new SimpleDateFormat("hh:mm", locale);
		try
		{
			Date date = sdf.parse(strDate);
			SimpleDateFormat sdf2 = new SimpleDateFormat("a", locale);
			return sdf2.format(date);
		}
		catch (ParseException e)
		{
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 특정 시간의 오전 정보만을 가져온다.
	 * 
	 * @param strDate
	 *            "HH:mm" 형태로 특정시간를 입력
	 * @return 12:00 이상일때 오전시간만을 반환
	 */
	public static String getOnlyAM(String strTime)
	{
		Locale locale = java.util.Locale.KOREA;
		SimpleDateFormat sdf = new SimpleDateFormat("hh:mm", locale);
		try
		{
			Date date = sdf.parse(strTime);
			return sdf.format(date);
		}
		catch (ParseException e)
		{
			e.printStackTrace();
		}

		return null;
	}

	public static boolean isPhoneNumber(String phoneNum)
	{
		Pattern p = Pattern.compile("01[016789][1-9]{1}[0-9]{2,3}[0-9]{4}$");
		Matcher matcher = p.matcher(phoneNum);

		return matcher.matches();
	}

	public static String toPhoneNumber(String phoneNum)
	{
		if(isNullorEmpty(phoneNum))
			return null;

		String result = "";
		int size = phoneNum.length();
		if(size == 10)
		{
			result = phoneNum.substring(0, 3) + "-" + phoneNum.substring(3, 6) + "-" + phoneNum.substring(6, 10);
		}
		else if(size == 11)
		{
			result = phoneNum.substring(0, 3) + "-" + phoneNum.substring(3, 7) + "-" + phoneNum.substring(7, 11);
		}

		return result;
	}

	public static String nullStringToBlank(String str)
	{
		if(isNullorEmpty(str))
			return "";

		return str;
	}

	public static int getStringNumber(String str)
	{
		int retVal = -1;
		if(isNullorEmpty(str))
		{
			return retVal;
		}
		else
		{
			try
			{
				retVal = Integer.parseInt(str);
			}
			catch (NumberFormatException e)
			{
				e.printStackTrace();
			}
			return retVal;
		}
	}

	/**
	 * 이메일 별처리
	 * 
	 * @param email
	 *            아이디
	 * @param count
	 *            별처리 할 자리수
	 * @param defStr
	 *            기본값(ex:비회원)
	 * @return
	 */
	public static String getHideEmail(String email, int count, String defStr)
	{
		if(isNullorEmpty(email))
			return defStr;

		String result = defStr;

		if(email.contains("@"))
		{
			String[] idStr = email.split("@");
			if(!isNullorEmpty(idStr[0]))
			{
				if(idStr[0].length() <= count)
				{
					result = idStr[0].replaceAll(".", "*") + "@" + idStr[1];
				}
				else
				{
					result = idStr[0].substring(0, idStr[0].length() - 2) + "**@" + idStr[1];
				}
			}
		}

		return result;
	}

	public static JSONArray getJsonArray(JSONArray targetArray, int count)
	{
		JSONArray resultArray = new JSONArray();

		if(targetArray == null || targetArray.length() == 0)
			return resultArray;

		try
		{
			int addIdx = 0;
			JSONObject job = null;
			int size = targetArray.length();
			for (int i = 0; i < size; i++)
			{
				if(i == 0)
				{
					job = new JSONObject();
					job.put(String.valueOf(i), targetArray.get(i));
				}
				else
				{
					if(i % count == 0)
					{
						resultArray.put(addIdx, job);
						addIdx++;

						job = null;
						job = new JSONObject();
					}

					job.put(String.valueOf(i % count), targetArray.get(i));
				}
			}

			if(job != null && job.length() != 0)
			{
				resultArray.put(addIdx, job);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return resultArray;
	}

	public static SpannableString getImgNumber(Context context, String text)
	{
		if(FormatUtil.isNullorEmpty(text))
			return new SpannableString("");

		SpannableString spanstr = new SpannableString(text);
		int size = text.length();
		for (int i = 0; i < size; i++)
		{
			String str = String.valueOf(text.charAt(i));
			GLog.e("str : " + str);
			int numResId = context.getResources().getIdentifier("text_num_" + str, "drawable", context.getPackageName());
			GLog.e("numResId : " + numResId);
			Drawable drawimg = context.getResources().getDrawable(numResId);
			drawimg.setBounds(0, 0, drawimg.getIntrinsicWidth(), drawimg.getIntrinsicHeight());
			ImageSpan span = new ImageSpan(drawimg, DynamicDrawableSpan.ALIGN_BOTTOM);
			spanstr.setSpan(span, i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		}

		return spanstr;
	}
}